"""
验证处理 request.data
验证器的参数
同时序列化多个对象
序列化的过程中添加上下文
无效的数据异常处理
"""
from django import forms
from django.contrib.auth.models import User
from rest_framework import serializers

from .models import Course


# 标准django序列化
class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ('name', 'introduction', 'teacher', 'price')


# REST framework 序列化
class CourseSerializer(serializers.ModelSerializer):

    # 外键字段 只读属性
    teacher = serializers.ReadOnlyField(source='teacher.username')

    class Meta:
        model = Course
        # exclude = ('id', )
        # fields = ('name', 'introduction', 'teacher', 'price')
        # 序列化全部字段
        fields = '__all__'
        # 遍历外键深度
        depth = 2

    def validate(self, data):
        """
        Check that start is before finish.
        """
        if data['price'] > 10:
            raise serializers.ValidationError("The price is to high")
        return data

# 接入链接url
# class CourseSerializer(serializers.HyperlinkedModelSerializer):
#     # 外键字段 只读属性
#     teacher = serializers.ReadOnlyField(source='teacher.username')
#
#     class Meta:
#         model = Course
#         # url是默认值， 可在settings.py 中设置URL_FIELD_NAME使全局生效
#         fields = ('name', 'url', 'introduction', 'teacher', 'price')


class UserSerializer(serializers.ModelSerializer):
    class Mete:
        model = User
        fields = '__all__'
